/*
 * OPIAM Suite
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package opiam.admin.applis.demo.servlets;

import opiam.admin.faare.MessageUtil;
import opiam.admin.faare.persistence.LdapObjectFilter;
import opiam.admin.faare.persistence.javabeans.JBTop;
import opiam.admin.faare.service.UserContext;
import opiam.admin.faare.service.services.StandardService;
import opiam.admin.faare.service.services.views.ViewGenerator;
import opiam.admin.faare.struts.utils.SessionContext;

import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.ByteArrayOutputStream;
import java.io.IOException;


/**
 * This servlet allows to download an orgchart file generated by the Views service.
 *<br>
 * HTTP PARAMETERS :<br>
 * <li>dn : entry dname</li>
 * <li>viewName  : view name</li>
 * <li>levelStr : number of levels</li>
 * <li>direction : orgchart type</li>
 * <li>mode : obsolete, should be 1</li>
 *<br>
 * WARNING : do not forget to configure the servlet in web.xml.
 */
public class PdfOrgChartServlet extends HttpServlet
{
    /** Log4j logger. */
    private static Logger _logger = Logger.getLogger(PdfOrgChartServlet.class);

    /**
     * Servlet processing method.
     * See HttpServlet.doGet
     *
     * @param request HTTP request
     * @param response HTTP response
     *
     * @throws java.io.IOException see HttpServlet
     * @throws javax.servlet.ServletException see HttpServlet
     */
    @Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
               throws IOException, ServletException
    {
        String dn = request.getParameter("dn");
        String viewName = request.getParameter("viewName");
        String levelStr = request.getParameter("levelStr");
        String direction = request.getParameter("direction");
        String mode = request.getParameter("mode");

        _logger.debug("dn = " + dn);
        _logger.debug("viewName = " + viewName);
        _logger.debug("levelStr = " + levelStr);
        _logger.debug("direction = " + direction);
        _logger.debug("mode = " + mode);

        if ((dn == null) || dn.trim().equals(""))
        {
            throw new ServletException(MessageUtil.getMessageString("MSG_ARGUMENT_NULL"));
        }

        if ((viewName == null) || viewName.trim().equals(""))
        {
            throw new ServletException(MessageUtil.getMessageString("MSG_ARGUMENT_NULL"));
        }

        if ((levelStr == null) || levelStr.trim().equals(""))
        {
            levelStr = "1";
        }

        if ((direction == null) || direction.trim().equals(""))
        {
            direction = "1";
        }

        if ((mode == null) || mode.trim().equals(""))
        {
            mode = "1";
        }

        try
        {
            int level = Integer.parseInt(levelStr);

            // Gets the session
            HttpSession session = request.getSession();

            // Gets the session context
            SessionContext sessionContext = SessionContext.getInstance(session);
            UserContext userContext = sessionContext.getUserContext();

            JBTop entry = StandardService.load(dn, userContext);
            userContext.getParameters().put(LdapObjectFilter.VAR_CURRENT_ITEM,
                                            entry
                                           );

            ByteArrayOutputStream output =
                ViewGenerator.generateOrgChart(entry, viewName, level,
                                               direction, mode, userContext
                                              );

            byte[] byteArray = output.toByteArray();
            _logger.debug("byteArray length : " + byteArray.length);
            response.setContentType("application/pdf");
            response.setHeader("Content-disposition",
                               "attachment; filename=orgchart.pdf"
                              ); 

            ServletOutputStream servletOutputStream =
                response.getOutputStream();

            servletOutputStream.write(byteArray, 0, byteArray.length);
            servletOutputStream.flush();

            // Flush and close streams
            servletOutputStream.close();
        }
        catch (Exception se)
        {
            se.printStackTrace();
        }
    }
}
